package com.company.project.controller.wx.demo;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


@RestController()
@RequestMapping("/wxdemo/auth")
public class WxOAuth2Controller {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMpService wxService;

    @RequestMapping("service")
    @ResponseBody
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String code = request.getParameter("code");
        try {
            response.getWriter().println("<h1>code</h1>");
            response.getWriter().println(code);

            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
            response.getWriter().println("<h1>access token</h1>");
            response.getWriter().println(wxMpOAuth2AccessToken.toString());

            WxMpUser wxMpUser = this.wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            response.getWriter().println("<h1>user info</h1>");
            response.getWriter().println(wxMpUser.toString());

            wxMpOAuth2AccessToken = this.wxService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            response.getWriter().println("<h1>after refresh</h1>");
            response.getWriter().println(wxMpOAuth2AccessToken.toString());

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        response.getWriter().flush();
        response.getWriter().close();

    }

    @RequestMapping("url")
    @ResponseBody
    public String getUrl()
    {
        WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = (WxMpInMemoryConfigStorage)wxService.getWxMpConfigStorage();
        wxMpInMemoryConfigStorage.setOauth2redirectUri("http://llwwbbb.tunnel.qydev.com/wxdemo/auth/service");
        String href = "<a href=\"" + wxService.oauth2buildAuthorizationUrl(
                wxService.getWxMpConfigStorage().getOauth2redirectUri(),
                WxConsts.OAUTH2_SCOPE_USER_INFO, null) + "\">测试oauth2</a>";
        return href;
    }

    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**geturl
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
     * @param args
     */
    public static void main(String[] args) {
        //第一步访问的url
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=wx846237de66a21364" +
                "&redirect_uri=" + urlEncodeUTF8("http://llwwbbb.tunnel.qydev.com/wxdemo/auth/service") +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=abc" +
                "#wechat_redirect";
        System.out.println("url:" + url);

    }


}
